<?php 
session_start();
header('Content-Type: text/html; charset=utf-8');
$f='not';
if (isset($_GET['f'])){
    $f=$_GET['f'];
}
include_once("./c/config.php");
$access_token = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$secret.'&code='.$_GET['code'].'&grant_type=authorization_code';
$access = file_get_contents($access_token);
$accessObj = json_decode($access);
$access_token = $accessObj->access_token;
$openid   = $accessObj->openid;
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$userInfoObj = json_decode(file_get_contents($user_info_url));
$mysqli = new mysqli($dbhost, $dbuser, $dbpwd, $dbName);
if (!$mysqli->set_charset("utf8")) {printf("Error loading character set utf8: %s\n", $mysqliTwo->error);}
if ($mysqli->connect_errno) {
    printf("failed: %s\n", $mysqli->connect_error);
    exit;
}
function filterEmoji($str)
{
    $str = preg_replace_callback(
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);
    
    return $str;
}
$sql="select id from users where openid='".$openid."'  limit 0,1 ";
$query = $mysqli->query($sql);
if($query->num_rows>0){
}else{
    $name=filterEmoji(addslashes(trim($userInfoObj->nickname)));
    $nickname=base64_encode($userInfoObj->nickname);
    $sql = "insert into users(openid,nickname,name,headimgurl,createtime) values ('".$openid."','".$nickname."','".$name."', '".$userInfoObj->headimgurl."', '".date("Y-m-d H:i:s")."' )";
    
    $mysqli->query($sql);
   
    $header = array(
    		'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
    		'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
    		'Accept-Encoding: gzip, deflate',);
    $url=$userInfoObj->headimgurl;
    $curl = curl_init();curl_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);$data = curl_exec($curl);$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);curl_close($curl);
    if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
    	$imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
    }
    $img_content=$imgBase64Code;//图片内容
    //echo $img_content;exit;
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result))
    {
    	$type = $result[2];//得到图片类型png?jpg?gif?
    	$new_file = "./upload/".$openid.".jpg";
    	if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))){}
    }
    
}
$_SESSION['openid']=$openid;
header('Location: /shell/?op='.$openid);
exit;